{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/klavis-ai/klavis/blob/main/examples/crewai/Use_Klavis_with_CrewAI.ipynb)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "# CrewAI + Klavis AI Integration\n",
    "\n",
    "This tutorial demonstrates how to use CrewAI with Klavis MCP (Model Context Protocol) servers to create powerful AI agent crews with access to external tools and services.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## Prerequisites\n",
    "\n",
    "- **OpenAI API key** - Get at [openai.com](https://openai.com/)\n",
    "- **Klavis API key** - Get at [klavis.ai](https://klavis.ai/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "# Install the required packages\n",
    "%pip install -qU crewai 'crewai-tools[mcp]' klavis openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from crewai import Agent, Task, Crew, Process\n",
    "from crewai_tools import MCPServerAdapter\n",
    "from klavis import Klavis\n",
    "from klavis.types import McpServerName\n",
    "\n",
    "# Set environment variables\n",
    "os.environ[\"OPENAI_API_KEY\"] = \"YOUR_OPENAI_API_KEY\"  # Replace with your actual OpenAI API key\n",
    "os.environ[\"KLAVIS_API_KEY\"] = \"YOUR_KLAVIS_API_KEY\"  # Replace with your actual Klavis API key\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## Case Study 1: YouTube Research Crew\n",
    "\n",
    "Let's create a CrewAI crew that can research YouTube videos using Klavis MCP servers.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "#### Step 1 - Create YouTube MCP Server using Klavis\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\ud83d\udd17 YouTube MCP server created at: https://youtube-mcp-server.klavis.ai/mcp/?instance_id=270cbd51-e737-407d-85ce-6e6162248671\n",
      "\ud83d\udcdd Instance ID: 270cbd51-e737-407d-85ce-6e6162248671\n"
     ]
    }
   ],
   "source": [
    "klavis_client = Klavis(api_key=os.getenv(\"KLAVIS_API_KEY\"))\n",
    "\n",
    "youtube_mcp_instance = klavis_client.mcp_server.create_server_instance(\n",
    "    server_name=McpServerName.YOUTUBE,\n",
    "    user_id=\"1234\",\n",
    ")\n",
    "\n",
    "print(f\"\ud83d\udd17 YouTube MCP server created at: {youtube_mcp_instance.server_url}\")\n",
    "print(f\"\ud83d\udcdd Instance ID: {youtube_mcp_instance.instance_id}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "#### Step 2 - Create CrewAI Agents with MCP Tools\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/zihaolin/src/klavis/.venv/lib/python3.13/site-packages/pydantic/fields.py:1093: PydanticDeprecatedSince20: Using extra keyword arguments on `Field` is deprecated and will be removed. Use `json_schema_extra` instead. (Extra keys: 'items', 'anyOf', 'enum', 'properties'). Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/\n",
      "  warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u2705 Available tools from YouTube MCP server: ['get_youtube_video_transcript']\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">/Users/zihaolin/src/klavis/.venv/lib/python3.13/site-packages/rich/live.py:231: UserWarning: install \"ipywidgets\" \n",
       "for Jupyter support\n",
       "  warnings.warn('install \"ipywidgets\" for Jupyter support')\n",
       "</pre>\n"
      ],
      "text/plain": [
       "/Users/zihaolin/src/klavis/.venv/lib/python3.13/site-packages/rich/live.py:231: UserWarning: install \"ipywidgets\" \n",
       "for Jupyter support\n",
       "  warnings.warn('install \"ipywidgets\" for Jupyter support')\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">```\n",
       "# YouTube Video Analysis: Andrej Karpathy - Software Is Changing (Again)\n",
       "\n",
       "## Video Details\n",
       "- **Title:** Andrej Karpathy: Software Is Changing (Again)\n",
       "- **Channel:** Y Combinator\n",
       "- **Published On:** June 19, 2025\n",
       "- **Duration:** 39:32\n",
       "- **View Count:** 1,035,413\n",
       "- **Like Count:** 33,783\n",
       "- **Comment Count:** 750\n",
       "- **Thumbnail:** ![Thumbnail](https://i.ytimg.com/vi/LCEmiRjPEtQ/hqdefault.jpg)\n",
       "\n",
       "## Key Insights Summary\n",
       "\n",
       "### Introduction\n",
       "- **[00:00 - Intro]**  \n",
       "  Andrej Karpathy introduces the topic of the keynote, discussing the evolution of software and the significance of\n",
       "new technological paradigms.\n",
       "\n",
       "### Software Evolution: From 1.0 to 3.0\n",
       "- **[01:25 - Software evolution: From 1.0 to 3.0]**  \n",
       "  Karpathy explains the major shifts in software development, highlighting that we are transitioning into \"Software\n",
       "3.0,\" where natural language processing (NLP) takes center stage.\n",
       "\n",
       "### Rise of Software 3.0\n",
       "- **[04:40 - Programming in English: Rise of Software 3.0]**  \n",
       "  In this segment, he emphasizes how the use of language models (LLMs) allows programmers to interact with software\n",
       "using English, democratizing programming.\n",
       "\n",
       "### LLMs as Utilities\n",
       "- **[06:10 - LLMs as utilities, fabs, and operating systems]**  \n",
       "  Karpathy compares LLMs to utilities and operating systems, proposing that they will be foundational to future \n",
       "software infrastructure.\n",
       "\n",
       "### New LLM OS\n",
       "- **[11:04 - The new LLM OS and historical computing analogies]**  \n",
       "  He discusses how current developments resemble the 1960s in computing history, pointing out the potential for new\n",
       "forms of computing to emerge.\n",
       "\n",
       "### Psychology of LLMs\n",
       "- **[14:39 - Psychology of LLMs: People spirits and cognitive quirks]**  \n",
       "  The discussion shifts to the psychological aspects of LLMs, referring to them as \"people spirits\" that simulate \n",
       "human-like capabilities while retaining unique flaws.\n",
       "\n",
       "### Designing LLM Apps\n",
       "- **[18:22 - Designing LLM apps with partial autonomy]**  \n",
       "  Karpathy suggests that LLM technology opens avenues for developing applications with varying degrees of autonomy.\n",
       "\n",
       "### Human-AI Collaboration\n",
       "- **[23:40 - The importance of human-AI collaboration loops]**  \n",
       "  Emphasizing the need for effective collaboration between humans and AI applications, he outlines strategies for \n",
       "fostering productive interactions.\n",
       "\n",
       "### Lessons from Tesla Autopilot\n",
       "- **[26:00 - Lessons from Tesla Autopilot &amp; autonomy sliders]**  \n",
       "  He shares lessons learned from Tesla\u2019s Autopilot system, detailing the implications for software development and \n",
       "user experience.\n",
       "\n",
       "### The Iron Man Analogy\n",
       "- **[27:52 - The Iron Man analogy: Augmentation vs. agents]**  \n",
       "  The comparison of LLMs to Iron Man's suit illustrates the concept of augmentation, emphasizing the potential for \n",
       "enhanced human capabilities.\n",
       "\n",
       "### Vibe Coding\n",
       "- **[29:06 - Vibe Coding: Everyone is now a programmer]**  \n",
       "  Karpathy explains 'vibe coding,' a concept where increased accessibility to programming via LLMs allows more \n",
       "people to engage in software development.\n",
       "\n",
       "### Future-Ready Digital Infrastructure\n",
       "- **[33:39 - Building for agents: Future-ready digital infrastructure]**  \n",
       "  He discusses the need to build a resilient and adaptable digital infrastructure that supports LLM-driven \n",
       "applications and agents.\n",
       "\n",
       "### Conclusion\n",
       "- **[38:14 - Summary: We\u2019re in the 1960s of LLMs \u2014 time to build]**  \n",
       "  In conclusion, he reflects on the current state of LLMs, advocating for innovation and building a new kind of \n",
       "computer that embraces the possibilities of software 3.0.\n",
       "\n",
       "## Main Takeaways\n",
       "- The transition to Software 3.0 marks a significant shift where natural language processing changes how we \n",
       "interact with technology.\n",
       "- LLMs have the potential to democratize programming, making it accessible to a broader audience.\n",
       "- Collaborative human-AI systems will define the future of software development, with a focus on adapting to new \n",
       "paradigms.\n",
       "- Historical computing analogies indicate that we are in the early stages of a transformative era, comparable to \n",
       "the 1960s in computing.\n",
       "\n",
       "## Additional Links\n",
       "- [Software 2.0 Blog Post](https://karpathy.medium.com/software-2-0-a64152b37c35)\n",
       "- [LLMs Flip the Script on Technology Diffusion](https://karpathy.bearblog.dev/power-to-the-people/)\n",
       "- [Vibe Coding MenuGen Retrospective](https://karpathy.bearblog.dev/vibe-coding-menugen/)\n",
       "```\n",
       "</pre>\n"
      ],
      "text/plain": [
       "```\n",
       "# YouTube Video Analysis: Andrej Karpathy - Software Is Changing (Again)\n",
       "\n",
       "## Video Details\n",
       "- **Title:** Andrej Karpathy: Software Is Changing (Again)\n",
       "- **Channel:** Y Combinator\n",
       "- **Published On:** June 19, 2025\n",
       "- **Duration:** 39:32\n",
       "- **View Count:** 1,035,413\n",
       "- **Like Count:** 33,783\n",
       "- **Comment Count:** 750\n",
       "- **Thumbnail:** ![Thumbnail](https://i.ytimg.com/vi/LCEmiRjPEtQ/hqdefault.jpg)\n",
       "\n",
       "## Key Insights Summary\n",
       "\n",
       "### Introduction\n",
       "- **[00:00 - Intro]**  \n",
       "  Andrej Karpathy introduces the topic of the keynote, discussing the evolution of software and the significance of\n",
       "new technological paradigms.\n",
       "\n",
       "### Software Evolution: From 1.0 to 3.0\n",
       "- **[01:25 - Software evolution: From 1.0 to 3.0]**  \n",
       "  Karpathy explains the major shifts in software development, highlighting that we are transitioning into \"Software\n",
       "3.0,\" where natural language processing (NLP) takes center stage.\n",
       "\n",
       "### Rise of Software 3.0\n",
       "- **[04:40 - Programming in English: Rise of Software 3.0]**  \n",
       "  In this segment, he emphasizes how the use of language models (LLMs) allows programmers to interact with software\n",
       "using English, democratizing programming.\n",
       "\n",
       "### LLMs as Utilities\n",
       "- **[06:10 - LLMs as utilities, fabs, and operating systems]**  \n",
       "  Karpathy compares LLMs to utilities and operating systems, proposing that they will be foundational to future \n",
       "software infrastructure.\n",
       "\n",
       "### New LLM OS\n",
       "- **[11:04 - The new LLM OS and historical computing analogies]**  \n",
       "  He discusses how current developments resemble the 1960s in computing history, pointing out the potential for new\n",
       "forms of computing to emerge.\n",
       "\n",
       "### Psychology of LLMs\n",
       "- **[14:39 - Psychology of LLMs: People spirits and cognitive quirks]**  \n",
       "  The discussion shifts to the psychological aspects of LLMs, referring to them as \"people spirits\" that simulate \n",
       "human-like capabilities while retaining unique flaws.\n",
       "\n",
       "### Designing LLM Apps\n",
       "- **[18:22 - Designing LLM apps with partial autonomy]**  \n",
       "  Karpathy suggests that LLM technology opens avenues for developing applications with varying degrees of autonomy.\n",
       "\n",
       "### Human-AI Collaboration\n",
       "- **[23:40 - The importance of human-AI collaboration loops]**  \n",
       "  Emphasizing the need for effective collaboration between humans and AI applications, he outlines strategies for \n",
       "fostering productive interactions.\n",
       "\n",
       "### Lessons from Tesla Autopilot\n",
       "- **[26:00 - Lessons from Tesla Autopilot & autonomy sliders]**  \n",
       "  He shares lessons learned from Tesla\u2019s Autopilot system, detailing the implications for software development and \n",
       "user experience.\n",
       "\n",
       "### The Iron Man Analogy\n",
       "- **[27:52 - The Iron Man analogy: Augmentation vs. agents]**  \n",
       "  The comparison of LLMs to Iron Man's suit illustrates the concept of augmentation, emphasizing the potential for \n",
       "enhanced human capabilities.\n",
       "\n",
       "### Vibe Coding\n",
       "- **[29:06 - Vibe Coding: Everyone is now a programmer]**  \n",
       "  Karpathy explains 'vibe coding,' a concept where increased accessibility to programming via LLMs allows more \n",
       "people to engage in software development.\n",
       "\n",
       "### Future-Ready Digital Infrastructure\n",
       "- **[33:39 - Building for agents: Future-ready digital infrastructure]**  \n",
       "  He discusses the need to build a resilient and adaptable digital infrastructure that supports LLM-driven \n",
       "applications and agents.\n",
       "\n",
       "### Conclusion\n",
       "- **[38:14 - Summary: We\u2019re in the 1960s of LLMs \u2014 time to build]**  \n",
       "  In conclusion, he reflects on the current state of LLMs, advocating for innovation and building a new kind of \n",
       "computer that embraces the possibilities of software 3.0.\n",
       "\n",
       "## Main Takeaways\n",
       "- The transition to Software 3.0 marks a significant shift where natural language processing changes how we \n",
       "interact with technology.\n",
       "- LLMs have the potential to democratize programming, making it accessible to a broader audience.\n",
       "- Collaborative human-AI systems will define the future of software development, with a focus on adapting to new \n",
       "paradigms.\n",
       "- Historical computing analogies indicate that we are in the early stages of a transformative era, comparable to \n",
       "the 1960s in computing.\n",
       "\n",
       "## Additional Links\n",
       "- [Software 2.0 Blog Post](https://karpathy.medium.com/software-2-0-a64152b37c35)\n",
       "- [LLMs Flip the Script on Technology Diffusion](https://karpathy.bearblog.dev/power-to-the-people/)\n",
       "- [Vibe Coding MenuGen Retrospective](https://karpathy.bearblog.dev/vibe-coding-menugen/)\n",
       "```\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">/Users/zihaolin/src/klavis/.venv/lib/python3.13/site-packages/rich/live.py:231: UserWarning: install \"ipywidgets\" \n",
       "for Jupyter support\n",
       "  warnings.warn('install \"ipywidgets\" for Jupyter support')\n",
       "</pre>\n"
      ],
      "text/plain": [
       "/Users/zihaolin/src/klavis/.venv/lib/python3.13/site-packages/rich/live.py:231: UserWarning: install \"ipywidgets\" \n",
       "for Jupyter support\n",
       "  warnings.warn('install \"ipywidgets\" for Jupyter support')\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Configure MCP server parameters for CrewAI\n",
    "server_params = {\n",
    "    \"url\": youtube_mcp_instance.server_url,\n",
    "    \"transport\": \"streamable-http\"\n",
    "}\n",
    "\n",
    "YOUTUBE_VIDEO_URL = \"https://www.youtube.com/watch?v=LCEmiRjPEtQ\"  # pick the video you want to analyze\n",
    "\n",
    "try:\n",
    "    with MCPServerAdapter(server_params) as mcp_tools:\n",
    "        print(f\"\u2705 Available tools from YouTube MCP server: {[tool.name for tool in mcp_tools]}\")\n",
    "        \n",
    "        # Create a YouTube Analysis Agent\n",
    "        youtube_agent = Agent(\n",
    "            role=\"YouTube Content Analyst\",\n",
    "            goal=\"Research and analyze YouTube videos to extract comprehensive insights and create structured summaries with timestamps\",\n",
    "            backstory=\"You are an expert at analyzing video content, extracting transcripts with precise timestamps, and creating professional summaries with key insights, takeaways, and time-coded references for easy navigation.\",\n",
    "            tools=mcp_tools,\n",
    "            reasoning=True,\n",
    "            verbose=False\n",
    "        )\n",
    "        \n",
    "        # Define Task\n",
    "        analysis_task = Task(\n",
    "            description=f\"Research the YouTube video at {YOUTUBE_VIDEO_URL}. Extract the video transcript, analyze the content, and create a comprehensive summary with key points, timestamps, and main takeaways. Structure it in a professional format.\",\n",
    "            expected_output=\"Complete video analysis with transcript, structured summary, key insights, timestamps, and main takeaways\",\n",
    "            agent=youtube_agent,\n",
    "            markdown=True\n",
    "        )\n",
    "        \n",
    "        # Create and execute the crew\n",
    "        youtube_crew = Crew(\n",
    "            agents=[youtube_agent],\n",
    "            tasks=[analysis_task],\n",
    "            verbose=False, # set to True to print the reasoning process\n",
    "            process=Process.sequential\n",
    "        )\n",
    "        \n",
    "        result = youtube_crew.kickoff()\n",
    "        print(result)\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"\u274c Error connecting to YouTube MCP server: {e}\")\n",
    "    print(\"Ensure the MCP server is running and accessible.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## Case Study 2: Multi-Service Research Crew with Gmail Integration\n",
    "\n",
    "Let's create a more complex crew that uses multiple MCP servers - YouTube for research and Gmail for communication.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "#### Step 1 - Create Gmail MCP Server (OAuth required)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">\ud83d\udd10 Opening OAuth authorization for Gmail...\n",
       "</pre>\n"
      ],
      "text/plain": [
       "\ud83d\udd10 Opening OAuth authorization for Gmail...\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import webbrowser\n",
    "\n",
    "gmail_mcp_instance = klavis_client.mcp_server.create_server_instance(\n",
    "    server_name=McpServerName.GMAIL,\n",
    "    user_id=\"1234\",\n",
    ")\n",
    "\n",
    "webbrowser.open(gmail_mcp_instance.oauth_url)\n",
    "\n",
    "print(f\"\ud83d\udd10 Opening OAuth authorization for Gmail...\")\n",
    "print(f\"\ud83d\udcf1 If not redirected automatically, open: {gmail_mcp_instance.oauth_url}\")\n",
    "# print(f\"\ud83d\udd17 Gmail MCP server will be available at: {gmail_mcp_instance.server_url}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "#### Step 2 - Create Multi-Service Crew with Multiple MCP Servers\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "VIDEO_URL = \"https://www.youtube.com/watch?v=LCEmiRjPEtQ\"  # pick the video you want to analyze\n",
    "RECIPIENT_EMAIL = \"zihaolin@klavis.ai\"  # Replace with your email\n",
    "\n",
    "\n",
    "# Configure multiple MCP servers\n",
    "multiple_server_params = [\n",
    "    {\n",
    "        \"url\": youtube_mcp_instance.server_url,\n",
    "        \"transport\": \"streamable-http\"\n",
    "    },\n",
    "    {\n",
    "        \"url\": gmail_mcp_instance.server_url,\n",
    "        \"transport\": \"streamable-http\"\n",
    "    }\n",
    "]\n",
    "\n",
    "try:\n",
    "    with MCPServerAdapter(multiple_server_params) as all_mcp_tools:\n",
    "        print(f\"\u2705 Available tools from all MCP servers: {[tool.name for tool in all_mcp_tools]}\")\n",
    "        \n",
    "        # Create YouTube Research Agent\n",
    "        youtube_research_agent = Agent(\n",
    "            role=\"YouTube Content Analyst\",\n",
    "            goal=\"Research and analyze YouTube videos to extract comprehensive insights and create structured summaries with timestamps\",\n",
    "            backstory=\"You are an expert at analyzing video content, extracting transcripts with precise timestamps, and creating professional summaries with key insights, takeaways, and time-coded references for easy navigation.\",\n",
    "            tools=mcp_tools,\n",
    "            reasoning=False,\n",
    "            verbose=False,\n",
    "        )\n",
    "        \n",
    "        # Create Email Communication Agent\n",
    "        email_agent = Agent(\n",
    "            role=\"Email Communications Specialist\",\n",
    "            goal=\"Draft and send professional email communications based on research findings\",\n",
    "            backstory=\"You are skilled at crafting professional emails and managing correspondence with clear, impactful messaging.\",\n",
    "            tools=mcp_tools,\n",
    "            reasoning=True,\n",
    "            verbose=False,\n",
    "        )\n",
    "        \n",
    "        # Define workflow tasks\n",
    "        youtube_research_task = Task(\n",
    "            description=f\"Research the YouTube video at {VIDEO_URL}. Extract transcript, analyze the content for key insights about AI and software development, and create a comprehensive analysis report with key takeaways and recommendations.\",\n",
    "            expected_output=\"Complete video analysis report with transcript, key insights, recommendations, and strategic takeaways\",\n",
    "            agent=youtube_research_agent\n",
    "        )\n",
    "        \n",
    "        send_email_task = Task(\n",
    "            description=f\"Based on the youtube analyze, draft and send a professional email to {RECIPIENT_EMAIL} with the subject 'Youtube video AI analysis'. Include content of the youtube video in the email.\",\n",
    "            expected_output=\"Confirmation that a professional email has been sent with the research insights\",\n",
    "            agent=email_agent,\n",
    "            context=[youtube_research_task]\n",
    "        )\n",
    "        \n",
    "        # Create and execute the crew\n",
    "        multi_service_crew = Crew(\n",
    "            agents=[youtube_research_agent, email_agent],\n",
    "            tasks=[youtube_research_task, send_email_task],\n",
    "            verbose=False, # set to True to print the reasoning process\n",
    "            process=Process.sequential\n",
    "        )\n",
    "        \n",
    "        result = multi_service_crew.kickoff()\n",
    "        print(result)\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"\u274c Error with multi-service MCP integration: {e}\")\n",
    "    print(\"Ensure all MCP servers are running and properly authenticated.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## Security Best Practices\n",
    "\n",
    "When using CrewAI with Klavis MCP servers, follow these security guidelines:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Example of secure MCP server configuration\n",
    "def create_secure_mcp_crew():\n",
    "    \"\"\"\n",
    "    Demonstrates secure MCP server integration with CrewAI\n",
    "    \"\"\"\n",
    "    # Use environment variables for sensitive data\n",
    "    api_key = os.getenv(\"KLAVIS_API_KEY\")\n",
    "    if not api_key:\n",
    "        raise ValueError(\"KLAVIS_API_KEY environment variable is required\")\n",
    "    \n",
    "    # Validate server URLs (use HTTPS in production)\n",
    "    server_params = {\n",
    "        \"url\": youtube_mcp_instance.server_url,\n",
    "        \"transport\": \"streamable-http\"\n",
    "    }\n",
    "    \n",
    "    # Always use context managers for proper resource cleanup\n",
    "    try:\n",
    "        with MCPServerAdapter(server_params) as mcp_tools:\n",
    "            # Validate available tools before use\n",
    "            if not mcp_tools:\n",
    "                raise ValueError(\"No tools available from MCP server\")\n",
    "            \n",
    "            print(f\"\u2705 Securely connected with {len(mcp_tools)} tools\")\n",
    "            return mcp_tools\n",
    "            \n",
    "    except Exception as e:\n",
    "        print(f\"\ud83d\udd12 Security check failed: {e}\")\n",
    "        return None\n",
    "\n",
    "# Example usage\n",
    "secure_tools = create_secure_mcp_crew()\n",
    "if secure_tools:\n",
    "    print(\"\u2705 Secure connection established successfully\")\n",
    "else:\n",
    "    print(\"\u274c Secure connection failed\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "vscode": {
     "languageId": "raw"
    }
   },
   "source": [
    "## Summary\n",
    "\n",
    "This tutorial demonstrated how to integrate CrewAI with Klavis MCP servers. We covered several key patterns:\n",
    "\n",
    "### \ud83c\udfaf **Key Features Demonstrated:**\n",
    "\n",
    "1. **Single Agent YouTube Analysis**: Using 1 agent with YouTube MCP server for comprehensive video analysis\n",
    "2. **Two-Agent Multi-Service Workflow**: YouTube research agent + Email communication agent using multiple MCP servers\n",
    "3. **Security Best Practices**: Secure configuration and error handling\n",
    "\n",
    "### \ud83d\ude80 **CrewAI + Klavis Benefits:**\n",
    "\n",
    "- **Seamless Integration**: MCPServerAdapter makes it easy to connect to Klavis MCP servers\n",
    "- **Agent Specialization**: Different agents can have access to different tools\n",
    "- **Efficient Workflows**: Streamlined crews with focused responsibilities\n",
    "- **Scalable Architecture**: Easy to add more MCP servers and tools\n",
    "- **Professional AI Crews**: Create sophisticated AI teams with real-world capabilities\n",
    "\n",
    "### \ud83d\udee0 **Available MCP Servers:**\n",
    "Klavis provides MCP servers for YouTube, Gmail, Google Drive, Slack, GitHub, and many more services - all easily integrable with CrewAI!\n",
    "\n",
    "**Happy crew building!** \ud83d\ude80\ud83d\udc65\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}